<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="q">
          <el-form-item label="文章分类">
            <el-select v-model="q.cate_id" placeholder="请选择分类" size="small">
              <el-option v-for="item in cateList" :key="item.id" :label="item.cate_name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px;">
            <el-select v-model="q.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="search">筛选</el-button>
            <el-button type="info" size="small" @click="reset">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button type="primary" size="small" class="btn-pub" @click="pubVisible = true">发表文章</el-button>
      </div>
      <!-- 文章表格区域 -->
      <el-table :data="artList" border stripe>
        <el-table-column label="文章标题" prop="title">
          <template v-slot="scope">
            <el-link type="primary" @click="showDetail(scope.row.id)">{{ scope.row.title }}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="分类" prop="cate_name"></el-table-column>
        <el-table-column label="发表时间">
          <template v-slot="scope">
            {{ scope.row.pub_date | dateFormat }}
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="state"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button type="danger" size="mini" @click="remove(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        :current-page="q.pagenum"
        :page-size="q.pagesize"
        :total="total"
        prev-text="上一页"
        next-text="下一页"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[2, 3, 5, 10]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange">
      </el-pagination>
    </el-card>
    <!-- 发表文章的对话框 -->
    <!-- 查看文章详情的对话框 -->
    <el-dialog title="文章预览" :visible.sync="detailVisible" width="80%">
      <h1 class="title">{{ artDetail.title }}</h1>
      <div class="info">
        <span>作者：{{ artDetail.username }}</span>
        <span>发布时间：{{ artDetail.pub_date | dateFormat }}</span>
        <span>所属分类：{{ artDetail.cate_name }}</span>
        <span>状态：{{ artDetail.state }}</span>
      </div>
      <!-- 分割线 -->
      <el-divider></el-divider>
      <!-- 文章的封面 -->
      <img :src="'http://www.liulongbin.top:3008' + artDetail.cover_img" alt="" class="cover-img" />
      <!-- 文章的详情 -->
      <div class="detail-box" v-html="artDetail.content"></div>
    </el-dialog>
    <el-dialog
      title="发表文章"
      :visible.sync="pubVisible"
      fullscreen
      :before-close="beforeClose"
      @closed="pubClosed">
      <!-- 发表文章的表单 -->
      <el-form :model="pubForm" :rules="pubRules" ref="pubRef" label-width="100px">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="pubForm.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="文章分类" prop="cate_id">
          <el-select v-model="pubForm.cate_id" placeholder="请选择分类" style="width: 100%;">
            <el-option v-for="item in cateList" :key="item.id" :label="item.cate_name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文章内容">
          <!-- 使用 v-model 进行双向的数据绑定 -->
          <quill-editor v-model="pubForm.content"></quill-editor>
        </el-form-item>
        <el-form-item label="文章封面">
          <!-- 用来显示封面的图片 -->
          <img src="../../../assets/images/cover.jpg" alt="" class="cover-img" ref="imgRef" />
          <br />
          <!-- 文件选择框，默认被隐藏 -->
          <input type="file" style="display: none;" accept="image/*" ref="fileRef" @change="fileChange" />
          <!-- 选择封面的按钮 -->
          <el-button type="text" @click="chooseImg">+ 选择封面</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="pubArticle('已发布')">发布</el-button>
          <el-button type="info" @click="pubArticle('草稿')">存为草稿</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 查看文章详情的对话框 -->
  </div>
</template>

<script>
import img from '@/assets/images/cover.jpg'
console.log(img)
export default {
  name: 'ArtList',
  data() {
    return {
      // 查询参数对象
      q: {
        // 当前是第几页
        pagenum: 1,
        // 每页展示多少条
        pagesize: 3,
        cate_id: '',
        state: ''
      },
      // 控制发布文章对话框的显示与隐藏
      pubVisible: false,
      // 表单的数据对象
      pubForm: {
        title: '',
        cate_id: '',
        content: '',
        cover_img: null,
        state: ''
      },
      // 表单的验证规则对象
      pubRules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          { min: 1, max: 30, message: '文章标题的长度为1-30个字符', trigger: 'blur' }
        ],
        cate_id: [
          { required: true, message: '请选择文章标题', trigger: 'change' }
        ]
      },
      // 文章分类的列表
      cateList: [],
      // 文章列表
      artList: [],
      // 总数
      total: 0,
      // 文章详情
      artDetail: {},
      // 控制文章详情对话框的显示与隐藏
      detailVisible: false
    }
  },
  created() {
    this.getCateList()
    this.getArtList()
  },
  methods: {
    // 对话框关闭前的回调
    beforeClose() {
      // 询问用户是否关闭
      this.$confirm('此操作将导致文章信息丢失, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 关闭对话框
        this.pubVisible = false
      }).catch(() => {
        // 点击取消，会走 catch
      })
    },
    // 获取文章分类列表
    async getCateList() {
      const { data: res } = await this.$http.get('/my/cate/list')
      if (res.code === 0) {
        this.cateList = res.data
      }
    },
    // 选择图片
    chooseImg() {
      this.$refs.fileRef.click()
    },
    fileChange(e) {
      console.log(e.target.value)
      const files = e.target.files
      if (files.length === 0) {
        console.log('没有选择图片')
      } else {
        // console.log(Object.prototype.toString.call(files[0]))
        // 给后端传递的文件字段赋值
        this.pubForm.cover_img = files[0]
        // 渲染前端页面的图片
        const url = URL.createObjectURL(files[0])
        this.$refs.imgRef.src = url
        // this.$refs.imgRef.setAttribute('src', url)
      }
    },
    // 发布文章
    pubArticle(state) {
      this.pubForm.state = state
      // 1. 表单预校验
      this.$refs.pubRef.validate(async valid => {
        // 校验不通过
        if (!valid) {
          this.$message.warning('请填写文章标题和分类！')
          return false
        }
        if (this.pubForm.content === '') {
          this.$message.warning('请填写文章内容！')
          return false
        }
        if (this.pubForm.cover_img === null) {
          this.$message.warning('请选择文章封面！')
          return false
        }

        const fd = new FormData()
        // fd.append('title', this.pubForm.title)
        // fd.append('cate_id', this.pubForm.cate_id)
        // fd.append('content', this.pubForm.content)
        // fd.append('cover_img', this.pubForm.cover_img)
        // fd.append('state', this.pubForm.state)

        // for (const key in this.pubForm) {
        //   fd.append(key, this.pubForm[key])
        // }

        Object.keys(this.pubForm).forEach(key => {
          fd.append(key, this.pubForm[key])
        })

        // 2. 发起请求
        const result = await this.$http.post('/my/article/add', fd)
        console.log(result.data)
        if (result.data.code === 0) {
          // 文章发表成功
          this.$message.success(result.data.message)
          // 关闭对话框
          this.pubVisible = false
          // 刷新文章列表数据
          // TODO
          this.getArtList()
        } else {
          // 文章发表失败
          this.$message.error(result.data.message)
        }
      })
    },
    // 发表文章的对话框关闭
    pubClosed() {
      // 重置表单
      this.$refs.pubRef.resetFields()
      this.pubForm.content = ''
      this.pubForm.cover_img = null
      this.pubForm.state = ''
      // 将图片渲染成默图片
      this.$refs.imgRef.src = img
      // 将选择图片的 input value 清空
      this.$refs.fileRef.value = ''
    },
    // 获取文章列表
    async getArtList() {
      const { data: res } = await this.$http.get('/my/article/list', {
        params: this.q
      })
      if (res.code === 0) {
        this.artList = res.data
        this.total = res.total
      } else {
        this.$message.error(res.message)
      }
    },
    // 每页展示多少条数据发生变化
    handleSizeChange(size) {
      console.log(size)
      this.q.pagesize = size
      this.q.pagenum = 1
      this.getArtList()
    },
    // 当前展示第几页变化
    handleCurrentChange(num) {
      console.log(num)
      this.q.pagenum = num
      this.getArtList()
    },
    // 筛选
    search() {
      this.q.pagenum = 1
      this.getArtList()
    },
    // 重置
    reset() {
      // 将条件恢复成默认值
      this.q = {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      }
      // 请求接口
      this.getArtList()
    },
    // 展示文章详情
    async showDetail(id) {
      const { data: res } = await this.$http.get('/my/article/info', {
        params: {
          id
        }
      })
      if (res.code === 0) {
        this.artDetail = res.data
        this.detailVisible = true
      } else {
        this.$message.error(res.message)
      }
    },
    // 删除
    remove(id) {
      // 1. 询问用户是否删除
      this.$confirm('此操作将永久删除该文章, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 点击确定，会走 then
        // 2. 发起请求
        const { data: res } = await this.$http.delete('/my/article/info', {
          params: {
            id
          }
        })
        if (res.code === 0) {
          // 删除成功
          this.$message.success(res.message)
          // this.q.pagenum = 1
          if (this.artList.length === 1 && this.q.pagenum > 1) {
            this.q.pagenum--
          }
          this.getArtList()
        } else {
          // 删除失败
          this.$message.error(res.message)
        }
      }).catch(() => {
        // 点击取消，会走 catch
      })
    }
  }
}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
}
// 设置富文本编辑器的默认最小高度
/deep/ .ql-editor {
  min-height: 300px;
}
// 设置图片封面的宽高
.cover-img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}
.el-pagination {
  margin-top: 15px;
}
.title {
  font-size: 24px;
  text-align: center;
  font-weight: normal;
  color: #000;
  margin: 0 0 10px 0;
}
.info {
  font-size: 12px;
  span {
    margin-right: 20px;
  }
}
// 修改 dialog 内部元素的样式，需要添加样式穿透
/deep/ .detail-box {
  img {
    width: 500px;
  }
}
</style>
